package com.quyunshuo.module.home.activity.main

import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.util.Log
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.Toast
import androidx.activity.viewModels
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import androidx.viewpager2.widget.ViewPager2
import com.quyunshuo.edwinmusictwo.base.utils.BarUtils.addMarginTopEqualStatusBarHeight
import com.quyunshuo.edwinmusictwo.common.ui.BaseActivity
import com.quyunshuo.module.home.adapter.ViewPagerAdapter
import com.quyunshuo.module.home.databinding.HomeActivityMainBinding
import com.quyunshuo.module.home.music.MusicPlayer
import com.quyunshuo.module.home.util.AppExit
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

@AndroidEntryPoint
class MainActivity : BaseActivity<HomeActivityMainBinding, SharedViewModel>() {
    companion object {
        fun newInstance(context: Context) {
            context.startActivity(Intent(context, MainActivity::class.java))
        }
    }

    private val REQUEST_READ_STORAGE = 101

    /**
     * 通过 viewModels() + Hilt 获取 ViewModel 实例
     */
    override val mViewModel by viewModels<SharedViewModel>()


    override fun createVB() = HomeActivityMainBinding.inflate(layoutInflater)


    override fun HomeActivityMainBinding.initView() {
        checkPermission()
        addMarginTopEqualStatusBarHeight(viewPager)
        // 创建适配器并设置
        val adapter = ViewPagerAdapter(this@MainActivity)
        viewPager.adapter = adapter

        // 监听页面变化更新按钮状态
        viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                when (position) {
                    0 -> {
                        toggleTabs(home)
                    }

                    1 -> {
                        toggleTabs(find)
                    }

                    2 -> {
                        toggleTabs(me)
                    }

                    else -> {
                        toggleTabs(setting)
                    }
                }
            }
        })

    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        Log.d("wenlong", "onNewIntent: ")
    }


    override fun HomeActivityMainBinding.initListener() {
        home.setOnClickListener {
            viewPager.currentItem = 0
            toggleTabs(home)
        }
        find.setOnClickListener {
            viewPager.currentItem = 1
            toggleTabs(find)
        }
        me.setOnClickListener {
            viewPager.currentItem = 2
            toggleTabs(me)
        }
        setting.setOnClickListener {
            viewPager.currentItem = 3
            toggleTabs(setting)
        }
        // 设置播放器回调
        MusicPlayer.setProgressCallback { current, total ->
            runOnUiThread {
                mViewModel.setProgress(current, total)
            }
        }
        MusicPlayer.setStateCallback { playing ->
            runOnUiThread {
                mViewModel.setIsPlaying(playing)
            }
        }
        MusicPlayer.setCurrentMusicCallback { music ->
            runOnUiThread {
                mViewModel.setCurrentMusic(music)
            }
        }

    }

    private fun toggleTabs(home: LinearLayout) {
        // 1行重置所有状态
        unSelTabs(listOf(mBinding.home, mBinding.find, mBinding.me, mBinding.setting))

        // 1行设置选中状态
        (home as? ViewGroup)?.getChildAt(0)?.isSelected = true  // 图标
        (home as? ViewGroup)?.getChildAt(1)?.isSelected = true  // 文本
    }

    private fun unSelTabs(listOf: List<LinearLayout>) {
        listOf.forEach {
            (it as? ViewGroup)?.getChildAt(0)?.isSelected = false  // 图标
            (it as? ViewGroup)?.getChildAt(1)?.isSelected = false  // 文本
        }

    }

    override fun initObserve() {


    }


    override fun initRequestData() {

    }

    override fun onBackPressed() {
        AppExit.onBackPressed(this)
    }

    private fun checkPermission() {
        //将权限检查移到后台线程（推荐）
        lifecycleScope.launch(Dispatchers.IO) {
            if (ContextCompat.checkSelfPermission(
                    this@MainActivity,
                    Manifest.permission.READ_EXTERNAL_STORAGE
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                ActivityCompat.requestPermissions(
                    this@MainActivity,
                    arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE),
                    REQUEST_READ_STORAGE
                )
            } else {
                mViewModel.loadMusic(this@MainActivity)
            }
        }

    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_READ_STORAGE) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                mViewModel.loadMusic(this@MainActivity)
            } else {
                Toast.makeText(
                    this,
                    "需要存储权限才能读取音乐文件",
                    Toast.LENGTH_SHORT
                ).show()
            }
        }
    }



}